the kubectl apply Command

Introduction

The kubectl apply command is essential for managing Kubernetes objects in a declarative way. In this post, we’ll explore how it functions, the importance of the last applied configuration, and how it compares the local configuration file, live object definition, and last applied configuration to determine changes needed in the cluster.

How kubectl apply Works

When you run the kubectl apply command:

For example, to create a Deployment from a configuration file:

kubectl apply -f deployment.yaml

Here, the content of deployment.yaml might look like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.19

Comparing Configurations

When a change is made to the local configuration file, such as updating the NGINX image version, running kubectl apply again will compare the following:

If differences are found, Kubernetes updates the live configuration accordingly. This ensures that the cluster is always in sync with the desired state defined in your local files.

The Importance of Last Applied Configuration

The last applied configuration is stored as an annotation on the live object in the Kubernetes cluster. It is crucial for tracking changes over time. If a field is removed from the local configuration, Kubernetes checks the last applied configuration to determine if that field should be removed from the live object. For example:

kubectl apply -f updated-deployment.yaml

If updated-deployment.yaml does not include a specific label present in the last applied configuration, that label will be removed from the live object.

Benefits of Using kubectl apply

When Not to Use kubectl apply

There are scenarios where using kubectl apply may not be the best choice:

Conclusion

Understanding how to effectively use the kubectl apply command is essential for managing Kubernetes resources. By leveraging the last applied configuration and comparing local files with live objects, you can ensure that your cluster's state aligns with your desired configuration. This approach not only streamlines management but also reduces the risk of errors during updates.

For more detailed information, please refer to the Kubernetes documentation.